package com.abs.orm.db.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.abs.orm.db.dao.util.DaoHelper;
import com.abs.orm.db.jdbc.ConnectionManager;
import com.abs.orm.db.jdbc.JdbcType;
import com.ads.orm.db.model.Column;
import com.ads.orm.db.model.Table;

public class DaoForOracle implements Dao {
	private static Dao dao;

	private DaoForOracle() {
		super();
	}

	public List<Table> getTables() {
		Connection conn = ConnectionManager.getConnection(JdbcType.Oracle);
		String tables[] = { "TABLE" };
		List<Table> list = new ArrayList<Table>();
		try {
			ResultSet rs = conn.getMetaData().getTables(null, conn.getMetaData().getUserName(), null, tables);
			Table table = null;
			while (rs.next()) {
				table = new Table();
				table.setTableName(rs.getString(3));
				list.add(table);
			}
			ConnectionManager.close(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	public void getColumns(Table table) {
		Connection conn = ConnectionManager.getConnection(JdbcType.Oracle);
		List<Column> list = new ArrayList<Column>();
		if (table != null && table.getTableName() != null) {
			try {
				Statement stmt = conn.createStatement();
				ResultSet rs = stmt.executeQuery("SELECT * FROM " + table.getTableName());
				Column column = null;
				ResultSetMetaData rsmd = rs.getMetaData();
				int count = rsmd.getColumnCount();
				for (int i = 1; i <= count; i++) {
					column = new Column();
					DaoHelper.RSMDToColumn(column, rsmd, i);
					list.add(column);
				}
				table.setColumns(list);
				ConnectionManager.close(rs);
				ConnectionManager.close(stmt);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static Dao getInstance() {
		if (null == dao) {
			dao = new DaoForOracle();
		}
		return dao;
	}
}
